﻿using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Utility;

namespace FrameWorkCore
{
    public static class JWTServices
    {
        public static void ConfigureJwt(this IServiceCollection services, IConfiguration configuration)
        {

            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = true,
                    ValidIssuer = configuration.GetValue<string>("JWT:ValidIssuer"),
                    ValidateAudience = true,
                    ValidAudience = configuration.GetValue<string>("JWT:ValidAudience"),
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration.GetValue<string>("JWT:SecurityKey"))),
                    ClockSkew = TimeSpan.Zero, 
                    ValidateLifetime = true,
                    RequireExpirationTime = true,
                };
                options.Events = new JwtBearerEvents()
                {
                    OnChallenge = context =>
                    {
                        //终止默认的返回结果(必须有)
                        context.HandleResponse();
                        context.Response.ContentType = "application/json";
                        //验证失败返回401
                        context.Response.StatusCode = StatusCodes.Status401Unauthorized;
                        context.Response.WriteAsync(
                        new
                        {
                            code = StatusCodes.Status401Unauthorized,
                            msg = "You have no authorization or token has failed! Please login again！"
                        }.ToJson());
                        return Task.FromResult(0);
                    }
                };


            });
        }
    }

}
